package zhao.tx.eecs.Tools;

import android.content.Context;

import java.io.File;
import java.util.List;

/**
 * Created by ishishuji on 14-7-21.
 */
public class BaseFileDeal {

    public static <T> void saveBaseFile ( Context context,String filePath , T value ) {

        File file = createFile ( context.getFilesDir ()+filePath );
        FileDataDeal.saveObjectToFile ( value,file );

    }

    public static void deleteBaseFile ( Context context , String filePath ) {
        delete ( context.getFilesDir () + filePath );
    }

    private static void delete ( String path ) {
        File file = new File ( path );
        if ( file.isFile () ) {
            file.delete ();
            return;
        }

        if ( file.isDirectory () ) {
            File[] childFiles = file.listFiles ();
            if ( childFiles == null || childFiles.length == 0 ) {
                file.delete ();
                return;
            }

            for ( int i = 0; i < childFiles.length; i++ ) {
                delete ( childFiles[ i ].getAbsolutePath () );
            }
            file.delete ();
        }
    }

    public static <T> T getBaseFile ( Context context , String filePath ) {
        if ( isFileExists ( context,filePath ) ) {
            File file = createFile ( context.getFilesDir ()+filePath );
            return FileDataDeal.getObjectToFile ( file );
        } else {
            return null;
        }
    }

    public static boolean isFileExists ( Context context , String filePath ) {

        File file = createFile ( context.getFilesDir ()+filePath );
        if ( file.exists () ) {
            return true;
        } else {
            return false;
        }
    }

    private static File createFile ( String path ) {
        File file = new File ( path );
        if ( file.isDirectory () ) {
            file.mkdirs ();
        }
        return file;
    }

}
